#include "answer.h"
#include "osmPathBuilder.h"

using namespace v8;

void AnswerJS::Init(v8::Handle<v8::Object> target)
{
    // Prepare constructor template
    Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
    tpl->SetClassName(String::NewSymbol("Answer"));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);
    // Prototype
    tpl->PrototypeTemplate()->Set(String::NewSymbol("reply"),
            FunctionTemplate::New(Reply)->GetFunction());

    Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());
    target->Set(String::NewSymbol("Answer"), constructor);
}

v8::Handle<v8::Value> AnswerJS::New(const v8::Arguments& args)
{
    HandleScope scope;

    return args.This();
}

v8::Handle<v8::Value> AnswerJS::Reply(const v8::Arguments& args)
{
    HandleScope scope;
    if (!args[0]->IsNumber() && !args[1]->IsNumber() && !args[2]->IsNumber())
        return scope.Close(Array::New(0));
    double lat=Handle<Number>::Cast(args[0])->Value();
    double lon=Handle<Number>::Cast(args[1])->Value();
    int beginId = Handle<Number>::Cast(args[2])->Value();
    int endId = Handle<Number>::Cast(args[3])->Value();
    int avoidPointsSize = Handle<Number>::Cast(args[4])->Value();
    std::vector<int> avoidPoints;
    if (avoidPointsSize > 0)
    {
        avoidPointsSize+=5;
        for (int i = 5; i < avoidPointsSize; i++)
        {
            avoidPoints.push_back(Handle<Number>::Cast(args[2])->Value());
        }
    }
    OsmPathBuilder* builder = new OsmPathBuilder(lat,lon);
    std::vector<int> shortestPath = builder->buildShortestPath(beginId,endId,avoidPoints);

    Handle<Array> messages = Array::New(shortestPath.size());

    for (int i = 0; i < shortestPath.size(); i++)
    {
        int currentId = shortestPath.at(i);
        Local<Object> jsobject = Object::New();
        jsobject->Set(String::NewSymbol("osm_id"), Number::New(currentId));
        messages->Set(i, jsobject);
    }

    return scope.Close(messages);
}

